﻿// ~~~~~ GLOBAL VALUES ~~~~~ //
var creatingNewFilter = false;
var categoryPaneExpanded = false;
var oddDefaultColour = "#fff";
var oddHighlightColour = "#efe";
var evenDefaultColour = "#eee";
var evenHighlightColour = "#ded";
var borderHighlightColour = "1px solid #0c0";
var borderDefaultColour = "1px solid #000";
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //



// ~~~~~ PAGE DEFAULT METHODS ~~~~~ //
function showLoadingBox() {
    //App.blockUI($('body'), false);
}
function hideLoadingBox() {
    //App.blockUI($('body'));
}
function applyDefaultRowColours() {
    $(".odd div").css("background", evenDefaultColour);
    $(".even div").css("background", oddDefaultColour);
}
function hideAllErrorMessages() {
    $(".error-message").hide();
}
function showFilterControls() {
    $("#filter-controls").slideDown(200);
}
function resetFilterControls(callback) {
    $("#filter-controls").slideUp(200, function () {
        $("#filter-name-textbox").val("");
        $("#filter-id").val("-1");
        $("#apply-button").hide();
        $("#filter-controls-create").hide();
        $("#group-select").get(0).selectedIndex = 0;
        $("#group-select").show();
        $("#new-group-name-textbox").hide();
        $("#new-group-name-textbox").val("");
        $("#new-group-name-link").show();
        $("#existing-group-link").hide();
        $("#filter-url-textbox").val("");
        $("#feature-select").get(0).selectedIndex = 0;
        $("#expression-select").get(0).selectedIndex = 0;
        $("#expression-select-container .value-textbox").val("");
        $("#expression-select-container .value-textbox").attr("rel", "0");
        $('#expression-select-container .value-textbox.last').hide();
        $('#expression-select-container .label-and').hide();
        $('#expression-select-container .box-value-filter').each(function () {
            $(this).remove();
        });
        $('#expression-select-container #add-button-value').hide();
        $("#use-in-catname").attr("checked", true);
        creatingNewFilter = false;
        hideAllErrorMessages();

        if (callback) callback();
    });
}
function clearSearchFields() {
    $("#search-filters-textbox").val("");
    $("#search-field-select").get(0).selectedIndex = 0;
}
function showApplyFiltersButton() {
    $("#apply-filters-button").animate({
        "top": "0"
    }, 500);
}
function hideApplyFiltersButton() {
    $("#apply-filters-button").animate({
        "top": "51px"
    }, 500);
}
function resetCategoryPane() {
    getWebsites();
    categories = [];
    drawCategories();
}
function expandCategoryPane() {
    categoryPaneExpanded = true;
    //$("#filters-container").animate({
    //    "width": "722px"
    //}, 200);
    $("#category-pane").animate({
        "width": "355px"
    }, 200);
    $("#category-pane-content").slideDown(200);
    $("#category-pane").css("height", "");
    $("#expand-category-pane").css("background-position", "57px 0");
    drawCategoryFiltersTable();
}
function collapseCategoryPane() {
    categoryPaneExpanded = false;
    $("#category-filters").hide();
    $("#category-pane-content").slideUp(200);
    $("#category-pane").animate({
        "height": "152px",
        "width": "0"
    }, 200);
    //$("#filters-container").animate({
    //    "width": "1050px"
    //}, 200);
    $("#expand-category-pane").css("background-position", "76px 0");
}
function showApplyConfirmation() {
    $("#popup-background").show();
    var box = $("#apply-confirmation");
    var top = ($(window).height() / 2) - ($(box).height() / 2) + $(window).scrollTop() - 50;
    $(box).css("top", top);
    var left = ($(window).width() / 2) - ($(box).width() / 2);
    $(box).css("left", left);
    $(box).show();
}
function hideApplyConfirmation() {
    $("#apply-confirmation").hide();
    $("#popup-background").hide();
}
function showRemoveCategoryFiltersConfirmation() {
    $("#popup-background").show();
    var box = $("#remove-category-filters-confirmation");
    var top = ($(window).height() / 2) - ($(box).height() / 2) + $(window).scrollTop() - 50;
    $(box).css("top", top);
    var left = ($(window).width() / 2) - ($(box).width() / 2);
    $(box).css("left", left);
    $(box).show();
}
function hideRemoveCategoryFiltersConfirmation() {
    $("#remove-category-filters-confirmation").hide();
    $("#popup-background").hide();
}
function showDeleteConfirmation() {
    $("#popup-background").show();
    var box = $("#remove-filters-confirmation");
    var top = ($(window).height() / 2) - ($(box).height() / 2) + $(window).scrollTop() - 50;
    $(box).css("top", top);
    var left = ($(window).width() / 2) - ($(box).width() / 2);
    $(box).css("left", left);
    $(box).show();
}
function hideDeleteConfirmation() {
    $("#remove-filters-confirmation").hide();
    $("#popup-background").hide();
}
function toggleSelectAllFilters(checkboxClass, checked) {
    if (checked) {
        $("." + checkboxClass).attr("checked", true);
    }
    else {
        $("." + checkboxClass).attr("checked", false);
    }
}
function toggleFilterRowHighlighting(tableID) {
    var rows = $("#" + tableID + " table tbody tr");
    for (var idx = 0, len = rows.length - 1; idx < len; idx++) { //-1 as last row is the filter count
        //get the checkbox in this row
        var checkbox = $($(rows[idx]).children("td")[0]).children("input");
        if ($(rows[idx]).attr("class") == "odd") {
            if ($(checkbox).attr("checked")) {
                $(rows[idx]).children("td").css("background-color", oddHighlightColour);
            }
            else {
                $(rows[idx]).children("td").css("background-color", oddDefaultColour);
            }
        }
        else {
            if ($(checkbox).attr("checked")) {
                $(rows[idx]).children("td").css("background-color", evenHighlightColour);
            }
            else {
                $(rows[idx]).children("td").css("background-color", evenDefaultColour);
            }
        }
    }
}
// ~~~~~~~~~~~~~~~~~~~~~ //

// ~~~~~ UTILITIES ~~~~~ //
String.prototype.contains = function(value) {
    if (value.length > this.length) return false;
    for (var idx = 0; idx <= this.length - value.length; idx++) {
        var bit = this.substr(idx, value.length);
        if (bit.toLowerCase() == value.toLowerCase()) {
            return true;
        }
    }
    return false;
}
function clearSelectBox(obj) {
    for (var idx = 0; idx < obj.options.length; ) {
        obj.options[idx] = null;
    }
}
function getCategoryFilterFromID(filterId) {
    for (var idx = 0, len = existingFiltersAll.length; idx < len; idx++) {
        if (existingFiltersAll[idx].CategoryFilterID == filterId) {
            return existingFiltersAll[idx];
        }
    }
    return null;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~ //

// ~~~~~ INITIALISATION ~~~~~ //
var matchingFilters = [];
var appliedSearches = [];
var existingFilters = [];
var existingFiltersAll = [];
var existingFiltersLoaded = false;
function getExistingFilters() {
    var response = $.ajax({
        type: "POST",
        url: "/intranet/CategoryFilterGetExistingFilters",
        complete: function() {
            try {
                var rtn = eval(response.responseText);
                existingFiltersAll = rtn;
                //sort the filters as filter names with numbers in will be in the wrong order
                existingFiltersAll = sortFiltersWithNumbers(existingFiltersAll);
                existingFilters = existingFiltersAll;
                existingFiltersLoaded = true;
                findMatchingFilters(true);
                addsearchValue();
                if (appliedSearches.length > 0) {
                    existingFilters = matchingFilters;
                }
                drawFiltersTable();
                if (checkForPageLoad()) {
                    hideLoadingBox();
                }
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
                loaded = true;
                hideLoadingBox();
            }
        }
    });
}
function sortFiltersWithNumbers(filters) {
    var sorting = true;
    while(sorting) {
        var noChanges = true;
        for (var idx = 0, len = filters.length - 1; idx < len; idx++) {
            var curFilter = filters[idx];
            var nextFilter = filters[idx + 1];
            if (curFilter.FilterGroupName == nextFilter.FilterGroupName) {
                //we want to compare them
                var curName = curFilter.FilterName.replace(/ /ig, "").replace(/''/ig, "\"");
                var nextName = nextFilter.FilterName.replace(/ /ig, "").replace(/''/ig, "\"");
                //now we have the two names... compare their values based on their format
                //a few regex's to look for
                var matchedRegex = false;
                var regexFeetOnly = /(([0-9]+)(?='))|(x)|(([0-9]+)(?='))/ig;
                //check for measurements with feet, ignoring the inches purely so the code isn't overly complex
                //for something that doesn't matter that much
                curNameBits = curName.match(regexFeetOnly);
                nextNameBits = nextName.match(regexFeetOnly);
                if ((curNameBits != null)&&(nextNameBits != null)
                    &&(curNameBits.length == 3)&&(nextNameBits.length == 3)
                    &&(curNameBits[1] == "x")&&(nextNameBits[1] == "x")
                ) {
                    matchedRegex = true;
                    //we have our feet values!
                    var curInt = parseInt(curNameBits[0]);
                    var nextInt = parseInt(nextNameBits[0]);
                    //just check they are numbers to stop errors even though they must be numbers!
                    if ((!isNaN(curInt))&&(!isNaN(nextInt))) {
                        if (curInt > nextInt) {
                            //swapsies
                            var filterTemp = filters[idx];
                            filters[idx] = filters[idx + 1];
                            filters[idx + 1] = filterTemp;
                            noChanges = false;
                        }
                        else if (curInt == nextInt) {
                            //we want to check the second number of each
                            curInt = parseInt(curNameBits[2]);
                            nextInt = parseInt(nextNameBits[2]);
                            if ((!isNaN(curInt))&&(!isNaN(nextInt))) {
                                if (curInt > nextInt) {
                                    var filterTemp = filters[idx];
                                    filters[idx] = filters[idx + 1];
                                    filters[idx + 1] = filterTemp;
                                    noChanges = false;
                                }
                            }
                        }
                    }
                }
                if (!matchedRegex) {
                    var regexFirstCharsNumbers = /[0-9]+/ig;
                    //check for names in general that start the first few characters as a number
                    curNameBits = curName.match(regexFirstCharsNumbers);
                    nextNameBits = nextName.match(regexFirstCharsNumbers);
                    if ((curNameBits != null)&&(nextNameBits != null)) {
                        matchedRegex = true;
                        var curInt = parseInt(curNameBits[0]);
                        var nextInt = parseInt(nextNameBits[0]);
                        if ((!isNaN(curInt))&&(!isNaN(nextInt))) {
                            if (curInt > nextInt) {
                                var filterTemp = filters[idx];
                                filters[idx] = filters[idx + 1];
                                filters[idx + 1] = filterTemp;
                                noChanges = false;
                            }
                        }
                    }
                }
            }
            else {
                //we dont want to compare them, so move on
                continue;
            }
        }
        if (noChanges) {
            sorting = false;
        }
    }
    return filters;
}
function resetExistingFilters() {
    existingFilters = existingFiltersAll;
}
function urlAlreadyExists(url, filterId) {
 
    for (var idx = 0, len = existingFilters.length; idx < len; idx++) {
        if (existingFilters[idx].FilterURL == url) {
            //if the filterId was supplied, check that this match isn't the same filter
            if (existingFilters[idx].CategoryFilterID != filterId) {
                return true;
            }
        }
    }
    return false;
}
function urlNotValid(url) {
    var pattern = /[^a-zA-Z0-9-]/ig;
    var match = url.match(pattern);
    if (match == null) return false;
    else return true;
}
function showAllFilters() {
    for (idx = 0, len = existingFilters.length; idx < len; idx++) {
        existingFilters[idx].Show = true;
    }
}

function drawFiltersTable(filterArray) {
    
    var filters = [];
    if (filterArray != null) filters = filterArray;
    else filters = existingFilters;
    
    //check that we're showing all relevant filters
    if (categoryFilters.length == 0) {
        //show them all
        showAllFilters();
    }
    
    var existingFiltersContainer = $("#existing-filters").get(0);
    $(existingFiltersContainer).html("");
    
    //create a table to hold the row data
    var table = document.createElement("table");
    existingFiltersContainer.appendChild(table);
    $(table).attr("class", "filter-table table table-fix").attr('data-height', '300');
    
    //create a thead for the headers
    var thead = document.createElement("thead");
    table.appendChild(thead);
    
    //fill in the column headers
    var headRow = thead.insertRow(-1);
    var headCell = headRow.insertCell(-1);
    var checkboxAll = document.createElement("input");
    checkboxAll.type = "checkbox";
    headCell.appendChild(checkboxAll);
    $(checkboxAll).attr("id", "all-filters-checkbox");
    $(checkboxAll).click(function(){
        toggleSelectAllFilters("filter-checkbox", $(this).attr("checked"));
        toggleFilterRowHighlighting("existing-filters");
        
    });
    headCell = headRow.insertCell(-1); //for the edit text
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "FilterName";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "FilterURL";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "FilterGroup";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "FeatureName";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "Use in cat name";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "Expression";
    var countValue = 0;
    for (var d = 0; d < filters.length; d++) {
        countValue = Math.max(countValue, filters[d].CountFilterValue);
    }

    for (var j = 1; j < countValue+1; j++) {
        headCell = headRow.insertCell(-1);
        headCell.innerHTML = "Value "+j;
    }
    
    //step through the filters array and draw a new row for each filter
    var tbody = document.createElement("tbody");
    table.appendChild(tbody);
    var count = 0;
    var CategoryFilterId = "";
    for (var idx = 0, len = filters.length; idx < len; idx++) {
        if (!filters[idx].Show) continue;
        var row = tbody.insertRow(-1);
        row.className = (count % 2 == 1) ? "even" : "odd";
        var cell = row.insertCell(-1);
        var checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        $(checkbox).attr("id", "filter-" + filters[idx].CategoryFilterID);
        $(checkbox).attr("class", "filter-checkbox");
        $(checkbox).click(function(){
            toggleFilterRowHighlighting("existing-filters");
        });
            cell.appendChild(checkbox);
            cell = row.insertCell(-1);
            $(cell).html($(cell).html() + " <a href='#' onclick='editFilter(" + filters[idx].CategoryFilterID + "); return false;'>edit</a>");
            cell = row.insertCell(-1);
            cell.innerHTML = filters[idx].FilterName;
            cell = row.insertCell(-1);
            cell.innerHTML = filters[idx].FilterURL;
            cell = row.insertCell(-1);
            cell.innerHTML = filters[idx].FilterGroupName;
            cell = row.insertCell(-1);
            cell.innerHTML = filters[idx].FeatureName;
            cell = row.insertCell(-1);
            cell.innerHTML = filters[idx].UseInCatName;
            cell = row.insertCell(-1);
            cell.innerHTML = filters[idx].Expression;
            if (filters[idx].FilterValue.indexOf('|') > -1) {
                var filtervalue = filters[idx].FilterValue.split('|');
                for (var i = 0; i < filtervalue.length; i++) {
                    if (filtervalue[i] != "")
                    {
                        cell = row.insertCell(-1);
                        var cellvalue = filtervalue[i].split('~');
                        cell.innerHTML = cellvalue[0];
                    }

                }
                for (var k = 0; k <= countValue - filtervalue.length; k++) {
                    cell = row.insertCell(-1);
                }
            } 
        //increment count that we use for the row classes
        count++;
    }
    
    //set up a row to use as a footer
    var footRow = table.insertRow(-1);
    footRow.className = "footer-row";
    var footCell = footRow.insertCell(-1);
    footCell = footRow.insertCell(-1);
    footCell.colSpan = 9;
    //get the number of filters 'showing'
    var count = filters.length;
    for (var idx = 0, len = filters.length; idx < len; idx++) {
        if (!filters[idx].Show) count--;
    }
    footCell.innerHTML = count + " match" + ((count != 1) ? "es" : "") + " out of " + 
        existingFiltersAll.length + " filter" + ((existingFiltersAll.length != 1) ? "s" : "");
}
function drawAppliedFilters() {
    var div = $("#applied-searches").get(0);
    $(div).html("<h3>Applied Searches</h3>");
    if (appliedSearches.length == 0) {
        $(div).hide();
        return;
    }
    $(div).show();
    var ul = document.createElement("ul");
    div.appendChild(ul);
    for (var idx = 0, len = appliedSearches.length; idx < len; idx++) {
        var li = document.createElement("li");
        ul.appendChild(li);
        var button = document.createElement("input");
        li.appendChild(button);
        button.type = "button";
        $(button).click(function() {
            var i = $(this).parent().attr("id").replace(/appliedSearch/, "");
            removeAppliedSearch(i);
        });
        $(button).val("X");
        $(button).attr("id", "appliedSearchButton" + idx);
        $(button).attr("class", "applied-search-button");
        $(li).attr("id", "appliedSearch" + idx);
        var label = document.createElement("label");
        li.appendChild(label);
        $(label).attr("for", "appliedSearchButton" + idx);
        $(label).html(" " + appliedSearches[idx].FieldName + ": " + appliedSearches[idx].SearchText + " ");
    }
}
function removeAppliedSearch(appliedSearchIdx) {
    appliedSearches.splice(appliedSearchIdx, 1);
    findMatchingFilters(true);
}
var filterGroups = [];
var filterGroupsLoaded = false;
function getFilterGroups() {
    var response = $.ajax({
        url: "/intranet/CategoryGetFilterGroups",
        complete: function() {
            try {
                var rtn = eval(response.responseText);
                filterGroups = rtn;
                filterGroupsLoaded = true;
                var groupSelect = $("#group-select").get(0);
                clearSelectBox(groupSelect);
                groupSelect.options[0] = new Option("-- choose group --", -1);
                for (var idx = 0, len = filterGroups.length; idx < len; idx++) {
                    groupSelect.options[idx + 1] = new Option(filterGroups[idx].FilterGroupName, filterGroups[idx].FilterGroupID);
                }
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
                loaded = true;
                hideLoadingBox();
            }
        }
    });
}
var featureNames = [];
var featureNamesLoaded = false;
function getFeatureNames() {
    var response = $.ajax({
        url: "/intranet/CategoryGetFeatureNames",
        complete: function() {
            try {
                var rtn = eval(response.responseText);
                featureNames = rtn;
                featureNamesLoaded = true;
                var featureSelect = $("#feature-select").get(0);
                clearSelectBox(featureSelect);
                featureSelect.options[0] = new Option("-- choose feature --", -1);
                for (var idx = 0, len = featureNames.length; idx < len; idx++) {
                    featureSelect.options[idx + 1] = new Option(featureNames[idx].FeatureName, featureNames[idx].FeatureID);
                }
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
            }
        }
    });
}
var filterExpressions = [];
var filterExpressionsLoaded = false;
function getFilterExpressions() {
    var response = $.ajax({
        url: "/intranet/CategoryGetFilterExpressions",
        complete: function() {
            try {
                var rtn = eval(response.responseText);
                filterExpressions = rtn;
                filterExpressionsLoaded = true;
                var expressionsSelect = $("#expression-select").get(0);
                clearSelectBox(expressionsSelect);
                expressionsSelect.options[0] = new Option("-- choose expression --", -1);
                for (var idx = 0, len = filterExpressions.length; idx < len; idx++) {
                    expressionsSelect.options[idx + 1] = new Option(filterExpressions[idx].Expression, filterExpressions[idx].ExpressionID);
                }
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
            }
        }
    });
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~ //
function editFilter(filterId) {
    resetFilterControls(function () {
        var filter = getCategoryFilterFromID(filterId);
        if (filter == null) return;

        var url = filter.FilterURL;
        var name = filter.FilterName;

        var groupIndex = 0;
        var groups = $("#group-select").get(0).options;
        for (var idx = 0, len = groups.length; idx < len; idx++) {
            if (groups[idx].value == filter.FilterGroupID) {
                groupIndex = idx;
                break;
            }
        }
        var featureIndex = 0;
        var features = $("#feature-select").get(0).options;
        for (var idx = 0, len = features.length; idx < len; idx++) {
            if (features[idx].value == filter.FeatureID) {
                featureIndex = idx;
                break;
            }
        }


        var expressionIndex = 0;
        var expressions = $("#expression-select").get(0).options;
        for (var idx = 0, len = expressions.length; idx < len; idx++) {
            if (expressions[idx].value == filter.CategoryFilterExpressionID) {
                expressionIndex = idx;
                break;
            }
        }
        var filterValue = filter.FilterValue;
        var useInCatName = filter.UseInCatName;

        $("#filter-id").val(filterId);
        $("#filter-url-textbox").val(url);
        $("#filter-name-textbox").val(name);
        $("#group-select").get(0).selectedIndex = groupIndex;
        $("#feature-select").get(0).selectedIndex = featureIndex;
        $("#expression-select").get(0).selectedIndex = expressionIndex;

        $('#expression-select-container  .value-textbox').each(function () {
            $(this).parent('.box-value-filter').remove();
            $(this).remove();

        });
        var textbox = "<input type='text'  class='value-textbox' rel='0'/>";

        if (filterValue.indexOf('|') != -1) 
        {
            var value = filterValue.split('|');

            for (var i = 0; i < value.length; i++) 
            {
                if (value[i] != "") 
                {
                    var textvalue = value[i].split('~');
                   
                    var buttondelete = "<input type='button'  id='DeleteFilterValue'/>";
                    if (i != 1) {

                        $("<div id='box-value" + i + "'class='box-value-filter'></div>").insertBefore('#expression-select-container #add-button-value');
                        var text = $(textbox).insertBefore('#expression-select-container #add-button-value').val(textvalue[0]).attr('rel', textvalue[1]);
                        $("#expression-select-container #box-value" + i).append(text);
                        $("#expression-select-container #box-value" + i).append(buttondelete);
                    }

                    else {
                        $(textbox).insertBefore('#expression-select-container #add-button-value').val(textvalue[0]).attr('rel', textvalue[1]);
                    }
             }

            }
        }

        $("#use-in-catname").attr("checked", useInCatName);
        showFilterControls();
        if ($('#expression-select').val() == 10) {
            $('#expression-select-container #DeleteFilterValue').each(function () {
                $(this).show();
            });
            $('#expression-select-container #add-button-value').show();
        }

    });
}
function saveFilter() {
   
    showLoadingBox();
    hideAllErrorMessages();
    var filterId = $("#filter-id").val();
    var filterUrl = $("#filter-url-textbox").val();
    var filterName = $("#filter-name-textbox").val();
    var filterGroupID = $("#group-select").val();
    var filterGroup = $("#new-group-name-textbox").val();
    var featureID = $("#feature-select").val();
    var expressionID = $("#expression-select").val();
    var value = "";
    $('#expression-select-container .value-textbox').each(function () {
        value += "|" + $(this).val()+"~"+$(this).attr('rel');
    });
   
    var useInCatName = ($("#use-in-catname").attr("checked")) ? "1" : "0";

    //validate input
    var errors = false;
    if (urlAlreadyExists(filterUrl, filterId)) {
        $("#filter-url-exists-error").show();
        errors = true;
    }
    else if (urlNotValid(filterUrl)) {
        $("#filter-url-error").show();
        errors = true;
    }
    else if (filterUrl.length == 0) {
        $("#filter-url-error").show();
        errors = true;
    }
    if (filterName.length == 0) {
        $("#filter-name-error").show();
        errors = true;
    }
    if ((filterGroupID == -1)&&(filterGroup.length == 0)) {
        $("#filter-group-error").show();
        errors = true;
    }
    if (featureID == -1) {
        $("#feature-error").show();
        errors = true;
    }
    if (
        (expressionID == -1)
        ||(value.length == 0))
       {
       $("#expression-error").show();
       errors = true;
    }
    if (errors) {
        hideLoadingBox();
        return;
    }

    filterName = encodeURIComponent(filterName);
    filterGroup = encodeURIComponent(filterGroup);
    filterUrl = encodeURIComponent(filterUrl);
    //value = encodeURIComponent(value);

   
    var qsParams = "filterid=" + filterId + "&filtername=" + filterName + "&filtergroupid=" + filterGroupID +
        "&filtergroup=" + filterGroup + "&filterurl=" + filterUrl + "&featureid=" + featureID + 
        "&expressionid=" + expressionID + "&value=" + value + "&useincatname=" + useInCatName;
   
    var response = $.ajax({
        type: "POST",
        url: "/intranet/CategorySaveFilter",
        data: qsParams,
        complete: function() {
            try {
                var rtn = eval(response.responseText)[0];
                //if there were no errors we have inserted/updated and need to reload the relevant sections
                if (rtn.status == "success") {
                    resetFilterControls();
                    getFilterGroups();
                    getExistingFilters();
                }
                else {
                    alert(rtn.message);
                } 
                //reset the search fields
                clearSearchFields();
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
            }
        }
    });
}
//delete Category Filter Value

function deleteCategoryFilterValue() {
    var filtervalueid = $('#expression-select-container #list-value-removed').val();

    var response = $.ajax({
        url: "/intranet/RemoveCategoryFilterValue",
        data: "filtervalueid=" + filtervalueid,
        complete: function () {
            try {
                if (response == "success") {
                    $('#expression-select-container #list-value-removed').val(0);
                }
                else {

                }
            }
            catch (e) {
                $("#ajax-error").html("There was an error removing filter. Please contact an administrator");
            }
        }
    });
    
}
function deleteSelectedFilters() {
    var checkboxes = $(".filter-checkbox:checked");
    if (checkboxes.length == 0) {
        alert("There has been an error, please contact an administrator");
        return;
    }
    var filterIds = [];
    for (var idx = 0, len = checkboxes.length; idx < len; idx++) {
        var id = $(checkboxes[idx]).attr("id").replace(/filter-/ig, "");
        filterIds.push(id);
    }
    filterIds = filterIds.join(",");
    var response = $.ajax({
        url: "/intranet/CategoryDeleteFilters",
        data: "filterids=" + filterIds,
        complete: function() {
            try {
                var rtn = eval(response.responseText);
                if (rtn.status = "success") {
                    getExistingFilters();
                }
                else {
                    alert(rtn.message);
                }
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
            }
            hideDeleteConfirmation();
        }
    });
}

function findMatchingFilters(doAppliedSearches) {
    var searchText = "";
    var targetField = "";
    var counter = 0;
    if (doAppliedSearches) {
        counter = appliedSearches.length;
        existingFilters = existingFiltersAll;
        drawAppliedFilters();
        if (counter == 0) {
            drawFiltersTable();
            return;
        }
    }
    else {
        counter = 1;
        searchText = $("#search-filters-textbox").val();
        if (searchText.length == 0) {
            drawFiltersTable();
            return;
        }
        targetField = $("#search-field-select").val();
    }
    for (var idx = 0, len = counter; idx < len; idx++) {
        if (doAppliedSearches) {
            searchText = appliedSearches[idx].SearchText;
            targetField = appliedSearches[idx].FieldName;
        }
        if (targetField != -1) {
            matchingFilters = [];
            if (targetField.contains('value')) 
            {
                var numbertarget = targetField.split('value')[1];
                
                for (var j = 0; j < existingFilters.length; j++)
                {
                    var filtervalue = existingFilters[j].FilterValue.split('|');
                    if (filtervalue.length > numbertarget) 
                    {
                            var val = filtervalue[numbertarget].split('~');
                            
                            if (val[0].contains(searchText)) {
                               matchingFilters.push(existingFilters[j]);
                            }
                    }
                 }
                   drawFiltersTable(matchingFilters);
             } 
            else {
                for (var jdx = 0, lenj = existingFilters.length; jdx < lenj; jdx++) {
                    if (existingFilters[jdx][targetField].contains(searchText)) {
                        matchingFilters.push(existingFilters[jdx]);
                    }
                }
                if (doAppliedSearches) {
                    existingFilters = matchingFilters;
                }
                drawFiltersTable(matchingFilters);  
            }
        }
        else 
        {
            drawFiltersTable();
            return;
        }
    }
}

// ~~~~~ CATEGORY FILTER CONTROLS ~~~~~ //
var websites = [];
function getWebsites() {
    var response = $.ajax({
        url: "/intranet/CategoryGetWebsites",
        complete: function() {
            try {
                var rtn = eval(response.responseText);
                websites = rtn;
                drawWebsites();
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
            }
        }
    });
}
function drawWebsites() {
    var websiteSelect = $("#website-select").get(0);
    clearSelectBox(websiteSelect);
    websiteSelect.options[0] = new Option("-- choose website --", -1);
    for (var idx = 0, len = websites.length; idx < len; idx++) {
        websiteSelect.options[idx + 1] = new Option(websites[idx].storeName, websites[idx].storeId);
    }
}
var categories = [];
function getCategories(storeId) {
    showLoadingBox();
    var response = $.ajax({
        url: "/intranet/FilterGetCategories",
        data: "storeId=" + storeId,
        complete: function() {
            try {
                var rtn = eval(response.responseText);
                categories = rtn;
                drawCategories();
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
            }
            hideLoadingBox();
        }
    });
}
function drawCategories() {
    var categorySelect = $("#category-select").get(0);
    clearSelectBox(categorySelect);
    if (categories.length > 0) {
        categorySelect.options[0] = new Option("-- choose category --", -1);
        for (var idx = 0, len = categories.length; idx < len; idx++) {
            categorySelect.options[idx + 1] = new Option(categories[idx].displayName + " (" + categories[idx].categoryName + ")", categories[idx].categoryId);
        }
    }
    else {
        categorySelect.options[0] = new Option("-- (choose a website from above) --", -1);
    }
    drawCategoryFiltersTable();
}
categoryFilters = [];
function getCategoryFilters(categoryId, storeId) {
    showLoadingBox();
    var response = $.ajax({
        url: "/intranet/GetCategoryFilters",
        data: "categoryid=" + categoryId + "&storeid=" + storeId,
        complete: function() {
            try {
                var rtn = eval(response.responseText);
                setCategoryFilters(rtn);
            }
            catch (e) {
                $("#ajax-error").html(response.responseText);
            }
            //run the check for filters to be applied
            checkIfFiltersCanBeApplied();
            hideLoadingBox();
        }
    });
}
function setCategoryFilters(filters) {
   
    categoryFilters = [];
    for (var idx = 0, len = filters.length; idx < len; idx++) {
        var id = filters[idx].CategoryFilterID;
        for (var jdx = 0, lenj = existingFiltersAll.length; jdx < lenj; jdx++) {
            if (existingFiltersAll[jdx].CategoryFilterID == id) {
                categoryFilters.push(existingFiltersAll[jdx]);
                categoryFilters[idx].CategoryFilterLinkID = filters[idx].CategoryFilterLinkID;
                existingFiltersAll[jdx].Show = false;
            }
        }
    }
    drawFiltersTable();
    drawCategoryFiltersTable();
}


    
    //anh
function drawCategoryFiltersTable() {
    var categoryFiltersContainer = $("#category-filters").get(0);
    $(categoryFiltersContainer).html("");
    $(categoryFiltersContainer).hide();
   
    //create a table
    var table = document.createElement("table");
    categoryFiltersContainer.appendChild(table);
    $(table).attr("class", "filter-table");
    
    //create a thead for the table
    var thead = document.createElement("thead");
    table.appendChild(thead);
    var headRow = thead.insertRow(-1);
    var headCell = headRow.insertCell(-1);
    var checkboxAll = document.createElement("input");
    checkboxAll.type = "checkbox";
    headCell.appendChild(checkboxAll);
    $(checkboxAll).attr("id", "all-category-filters-checkbox");
    $(checkboxAll).click(function(){
        toggleSelectAllFilters("category-filter-checkbox", $(this).attr("checked"));
        toggleFilterRowHighlighting("category-filters");
    });
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "FilterName";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "FilterURL";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "FilterGroup";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "FeatureName";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "Use in cat name";
    headCell = headRow.insertCell(-1);
    headCell.innerHTML = "Expression";
    var countValue = 0;
        for (var d = 0; d < categoryFilters.length; d++) {
            countValue = Math.max(countValue, categoryFilters[d].CountFilterValue);
    }

    for (var j = 1; j < countValue + 1; j++) {
        headCell = headRow.insertCell(-1);
        headCell.innerHTML = "Value " + j;
    }
    //create the tbody
    var tbody = document.createElement("tbody");
    table.appendChild(tbody);
    for (var idx = 0, len = categoryFilters.length; idx < len; idx++) {
        var row = tbody.insertRow(-1);
        $(row).attr("class", ((idx % 2 == 1) ? "even" : "odd"));
        //get the filter this link has
        var filter = categoryFilters[idx];
        if (filter == null) continue;
        var cell = row.insertCell(-1);
        var checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        cell.appendChild(checkbox);
        $(checkbox).attr("id", "category-filter-link-" + categoryFilters[idx].CategoryFilterLinkID);
        $(checkbox).attr("rel", "category-filter-id-" + categoryFilters[idx].CategoryFilterID);
        $(checkbox).attr("class", "category-filter-checkbox");
        $(checkbox).click(function(){
            toggleFilterRowHighlighting("category-filters");
        });
        cell = row.insertCell(-1);
        $(cell).html(filter.FilterName);
        cell = row.insertCell(-1);
        $(cell).html(filter.FilterURL);
        cell = row.insertCell(-1);
        $(cell).html(filter.FilterGroupName);
        cell = row.insertCell(-1);
        $(cell).html(filter.FeatureName);
        cell = row.insertCell(-1);
        $(cell).html(filter.UseInCatName);
        cell = row.insertCell(-1);
        $(cell).html(filter.Expression);
       

        if (categoryFilters[idx].FilterValue.indexOf('|') > -1) {
            var filtervalue = categoryFilters[idx].FilterValue.split('|');
            for (var i = 0; i < filtervalue.length; i++) {
                if (filtervalue[i] != "") {
                    cell = row.insertCell(-1);
                    var cellvalue = filtervalue[i].split('~');
                    cell.innerHTML = cellvalue[0];
                }

            }
            for (var k = 0; k <= countValue - filtervalue.length; k++) {
                cell = row.insertCell(-1);
            }
        } 
    }
    
    //create the footer row to show the count
    var footRow = table.insertRow(-1);
    footRow.className = "footer-row";
    var footCell = footRow.insertCell(-1);
    footCell = footRow.insertCell(-1);
    footCell.colSpan = 9;
    footCell.innerHTML = categoryFilters.length + " filter" + ((categoryFilters.length != 1) ? "s" : "");
    
    //show the container
    if (($("#website-select").val() != -1)&&($("#category-select").val() != -1)) {
        $(categoryFiltersContainer).show();
    }
}
function checkIfFiltersCanBeApplied() {
    var filtersSelected = false;
    var checked = $(".filter-checkbox:checked");
    if (checked.length > 0) filtersSelected = true;
    var categorySelected = false;
    if ($("#category-select").val() != -1) categorySelected = true;
    if (filtersSelected && categorySelected) {
        showApplyFiltersButton();
    }
    else {
        hideApplyFiltersButton();
    }
}
function applySelectedFiltersToCategory() {
    hideApplyConfirmation();
    showLoadingBox();
    var items = $(".filter-checkbox:checked");
    var filterIDs = [];
    for (var idx = 0, len = items.length; idx < len; idx++) {
        var id = $(items[idx]).attr("id").replace(/filter-/ig, "");
        filterIDs.push(id);
    }
    var categoryId = $("#category-select").val();
    var storeId = $("#website-select").val();
    if ((filterIDs.length > 0)&&(categoryId != -1)&&(storeId != -1)) {
        var qsParams = "filterids=" + filterIDs.join(",") + "&categoryid=" + categoryId + "&storeId=" + storeId;
        var response = $.ajax({
            url: "/intranet/ApplyFiltersToCategory",
            data: qsParams,
            complete: function() {
                try {
                    var rtn = eval(response.responseText)[0];
                    if (rtn.status == "error") {
                        alert(rtn.message);
                    }
                }
                catch (e) {
                    $("#ajax-error").html(response.responseText);
                }
                //update the tables
                getCategoryFilters(categoryId, storeId);
                hideLoadingBox();
            }
        });
    }
    clearSearchFields();
}
function removeSelectedCategoryFilters() {
    hideRemoveCategoryFiltersConfirmation();
    showLoadingBox();
    var filters = $(".category-filter-checkbox:checked");
    var filterLinkIDs = [];
    for (var idx = 0, len = filters.length; idx < len; idx++) {
        var linkID = $(filters[idx]).attr("id").replace(/category-filter-link-/ig, "");
        filterLinkIDs.push(linkID);
        var id = $(filters[idx]).attr("rel").replace(/category-filter-id-/ig, "");
        //remove from categoryFilters
        for (var jdx = 0; jdx < categoryFilters.length; jdx++) {
            if (categoryFilters[jdx].CategoryFilterID == id) {
                categoryFilters.splice(jdx, 1);
                break;
            }
        }
        //toggle to 'show' in existingFilters
        for (var jdx = 0, lenj = existingFilters.length; jdx < lenj; jdx++) {
            if (existingFilters[jdx].CategoryFilterID == id) {
                existingFilters[jdx].Show = true;
            }
        }
    }
    //run the ajax
    var categoryID = $("#category-select").val();
    var storeID = $("#website-select").val();
    if ((categoryID != -1)&&(storeID != -1)&&(filterLinkIDs.length > 0)) {
        var response = $.ajax({
            url: "/intranet/RemoveFiltersFromCategory",
            data: "filterlinkids=" + filterLinkIDs.join(","),
            complete: function() {
                try {
                    var rtn = eval(response.responseText);
                    alert(rtn.message);
                }
                catch (e) {
                    $("#ajax-error").html(response.responseText);
                }
                //update the tables
                getCategoryFilters(categoryID, storeID);
                //reset the search fields as they wont apply anymore
                clearSearchFields();
                hideLoadingBox();
            }
        });
    }
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //

// ~~~~~ DOCUMENT READY FUNCTIONS ~~~~~ //
var loaded = false;
function checkForPageLoad() {
    if (existingFiltersLoaded
        &&filterGroupsLoaded
        &&featureNamesLoaded
        &&filterExpressionsLoaded) {
        loaded = true;
    }
    if (loaded == false) {
        setTimeout(function() { checkForPageLoad() }, 500);
    }
    else {
        $("#create-new-filter-button").attr("disabled", false);
        hideLoadingBox();
    }
}
//~~~~~ ADD FILTER VALUE~~~~

function AddFilterValue() {
    $('#expression-select-container #add-button-value').click(function () {
        var textbox = "<input type='text'  class='value-textbox add-text' rel='0'/>";
        $(textbox).insertBefore(this);
    });

}

function addsearchValue() {
    var maxfilterValue = 0;
    for (var i = 0; i < existingFilters.length; i++) {
        maxfilterValue = Math.max(maxfilterValue, existingFilters[i].CountFilterValue);
    }
    $('#search-filters #search-field-select option.rel').remove();
    for (var j = 1; j <= maxfilterValue; j++) {
        var optionselect = "<option class='rel' value='value" + j + "'>Value " + j + "</option>";
        $('#search-filters #search-field-select').append(optionselect);
    }
   
    
}
var timeoutObj = null;
$(document).ready(function () {
    AddFilterValue();
    $("#create-new-filter-button").attr("disabled", true);
    //initilisation of page objects
    $("#applied-searches").hide();
    getExistingFilters();
    getFilterGroups();
    getFeatureNames();
    getFilterExpressions();
    resetFilterControls();
    clearSearchFields();
    resetCategoryPane();
    collapseCategoryPane();

    checkForPageLoad();
    //remove category filter value
    $('#expression-select-container #DeleteFilterValue').click(function () {

        var filtervalueid = $(this).parent('.box-value-filter').find('.value-textbox').attr('rel');
        $('#expression-select-container #list-value-removed').val($('#expression-select-container #list-value-removed').val() + "," + filtervalueid);
        $(this).parent('.box-value-filter').remove();

    });

    //reset the height of the popup background
    $("#popup-background").css("height", $(document).height() + 70);

    //event handling
    $("#create-new-filter-button").click(function () {
        resetFilterControls(showFilterControls);



    });
    $("#hide-filter-controls-button").click(function () {
        resetFilterControls();
    });
    $("#delete-filters-button").click(function () {
        if ($(".filter-checkbox:checked").length > 0) {
            showDeleteConfirmation();
        }
    });
    $("#apply-filters-button").hover(function () {
        $(this).css("background-position", "0 40px");
    }, function () {
        $(this).css("background-position", "0 60px");
    });
    $("#apply-filters-button").mousedown(function () {
        $(this).css("background-position", "0 20px");
    });
    $("#apply-filters-button").mouseup(function () {
        $(this).css("background-position", "0 40px");
    });
    $("#apply-filters-button").click(function () {
        if (!categoryPaneExpanded) {
            expandCategoryPane();
        }
        showApplyConfirmation();
    });
    $("#expression-select").change(function () {
        //show/hide value2 box based on expressions

        if ($(this).val() == 10) {

            $('#expression-select-container .value-textbox.last').show();
            $('#expression-select-container .label-and').show();
            $('#expression-select-container #add-button-value').show();
        } else {
            $('#expression-select-container #add-button-value').hide();
            var countText = $('#expression-select-container .value-textbox').length;
            $('#expression-select-container .value-textbox').each(function () {
                if ($(this).hasClass('add-text') && $(this).val() == "") {
                    $(this).remove();
                }
            });
            if ($(this).val() == 2 || $(this).val() == 3) {
                $('#expression-select-container #DeleteFilterValue').each(function () {
                    $(this).show();
                });
                $('#expression-select-container #box-value2 #DeleteFilterValue').hide();
                if ($('#expression-select-container .value-textbox').hasClass('last')) { }
                else {
                    if (countText == 1) {
                        //$("<label class='label-and'> and </label>").insertBefore('#expression-select-container #add-button-value').hide();
                        $("<input class='value-textbox last' type='text' rel='0'/>").insertBefore('#expression-select-container #add-button-value').hide();

                    }
                }
                $('#expression-select-container .value-textbox.last').show();
                $('#expression-select-container .label-and').show();


            }

            else {

                $('#expression-select-container .value-textbox.last').hide();
                $('#expression-select-container .label-and').hide();
                $('#expression-select-container #DeleteFilterValue').each(function () {
                    $(this).show();
                });

            }

        }

    });
    $("#new-group-name-link").click(function (e) {
        e.preventDefault();
        $("#group-select").hide();
        $("#group-select").get(0).selectedIndex = 0;
        $("#new-group-name-textbox").show();
        $("#existing-group-link").show();
        $(this).hide();
    });
    $("#existing-group-link").click(function (e) {
        e.preventDefault();
        $("#new-group-name-textbox").hide();
        $("#new-group-name-textbox").val("");
        $("#new-group-name-link").show();
        $("#group-select").show();
        $(this).hide();
    });
    $("#cancel-button").click(function () {
        creatingNewFilter = false;
        resetFilterControls();
        applyDefaultRowColours();
    });
    $("#save-button").click(function (e) {
        deleteCategoryFilterValue();
        saveFilter();
    });
    $("#search-filters-textbox").focus(function () {
        $(this).css("border", borderHighlightColour);
    });
    $("#search-filters-textbox").blur(function () {
        $(this).css("border", borderDefaultColour);
    });
    $("#search-filters-textbox").keyup(function () {
        if (timeoutObj != null) {
            clearTimeout(timeoutObj);
        }
        timeoutObj = setTimeout(findMatchingFilters, 250);
    });
    $("#search-field-select").focus(function () {
        $(this).css("border", borderHighlightColour);
    });
    $("#search-field-select").blur(function () {
        $(this).css("border", borderDefaultColour);
    });
    $("#search-field-select").change(function () {
        findMatchingFilters();
    });
    $("#search-filters-apply-button").click(function () {
        var searchText = $("#search-filters-textbox").val();
        var fieldName = $("#search-field-select").val();
        if ((searchText.length == 0) || (fieldName == -1)) {
            $("#search-error").show();
            return;
        }
        $("#search-error").hide();
        appliedSearches.push({ FieldName: $("#search-field-select").val(), SearchText: $("#search-filters-textbox").val() });
        drawAppliedFilters();
        existingFilters = matchingFilters;
        clearSearchFields();
    });
    $("#clear-search-fields").click(function () {
        clearSearchFields();
        drawFiltersTable();
    });
    $("#expand-category-pane").hover(function () {
        if (categoryPaneExpanded) {
            $(this).css("background-position", "19px 0");
        }
        else {
            $(this).css("background-position", "38px 0");
        }
    }, function () {
        if (categoryPaneExpanded) {
            $(this).css("background-position", "57px 0");
        }
        else {
            $(this).css("background-position", "76px 0");
        }
    });
    $("#expand-category-pane").click(function () {
        if (categoryPaneExpanded) {
            collapseCategoryPane();
        }
        else {
            expandCategoryPane();
        }
    });
    $("#website-select").change(function () {
        var storeId = $(this).val();
        if (storeId == -1) {
            categories = [];
            categoryFilters = [];
            drawCategories();
            drawFiltersTable();
        }
        else {
            getCategories(storeId);
        }
    });
    $("#category-select").change(function () {
        var categoryId = $(this).val();
        if (categoryId == -1) {
            categoryFilters = [];
            drawFiltersTable();
            drawCategoryFiltersTable();
        }
        else {
            getCategoryFilters(categoryId, $("#website-select").val());
        }
    });
    $("#apply-confirm-yes-button").click(function () {
        applySelectedFiltersToCategory();
    });
    $("#apply-confirm-no-button").click(function () {
        hideApplyConfirmation();
    });
    $("#remove-filters-from-category-button").click(function () {
        if ($(".category-filter-checkbox:checked").length > 0) {
            showRemoveCategoryFiltersConfirmation();
        }
    });
    $("#remove-filters-yes-button").click(function () {
        removeSelectedCategoryFilters();
    });
    $("#remove-filters-no-button").click(function () {
        hideRemoveCategoryFiltersConfirmation();
    });
    $("#confirm-delete-filters-button").click(function () {
        deleteSelectedFilters();
    });
    $("#cancel-delete-filters-button").click(function () {
        hideDeleteConfirmation();
    });
    $("#popup-background").click(function () {
        hideApplyConfirmation();
        hideDeleteConfirmation();
    });
    $(document).keyup(function (e) {
        if (e.keyCode == 27) {
            hideDeleteConfirmation();
            hideApplyConfirmation();
            hideRemoveCategoryFiltersConfirmation();
        }
        checkIfFiltersCanBeApplied();
    });
    $(document).click(function (e) {
        checkIfFiltersCanBeApplied();
    });
});